﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using FFmpegVideoClip.Configuration;
using FFmpegVideoClip.Lib;
using FFmpegVideoClip.Lib.AdvancedFragmentProcessor;
using FFmpegVideoClip.Lib.UtilityControlsTools;

namespace FFmpegVideoClip.windows
{
    /// <summary>
    /// ProcessorSettings.xaml 的交互逻辑
    /// </summary>
    public partial class ProcessorSettings : Window
    {
        public ProcessorSettings()
        {
            InitializeComponent();
            this.DragTitle.PreviewMouseLeftButtonDown += DragTitle_PreviewMouseLeftButtonDown;
        }


        private void DragTitle_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)=>this.DragMove();
        public static void ShowSettingsDialog()
        {
            ProcessorSettings ts = new ProcessorSettings();
            ts.Owner = Application.Current.MainWindow;
            ts.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            ts.ShowDialog();
        }
        
        
        private void AddProcessorButton_Click(object sender, RoutedEventArgs e) => Config.AddProcessor(this, new());
        private void SchemeSaveAs_Button_Click(object sender, RoutedEventArgs e)
        {
            if (SchemeList.SelectedItem is null || SchemeList.SelectedItem is not AdvancedParametersSchemeModule module)
            {
                MessageBoxEx.Show(this, "请选择要另存的项目", "选择错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (!InputTextWindow.ShowInputTextDialog(this, "处理方案名称", out string Result))
                return;

            Config.AddSchemeModule(this, module.DeepCopy().SetName(Result), Config.Instance.SchemeModules.IndexOf(module) + 1);
        }
        private void NewAddScheme_Button_Click(object sender, RoutedEventArgs e)
        {
            Config.AddSchemeModule(this, new());
        }
        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (TabPages.SelectedIndex == 0 && SchemeList.SelectedIndex > -1)
                Config.Instance.SchemeModules.Remove((AdvancedParametersSchemeModule)SchemeList.SelectedItem);
            if (TabPages.SelectedIndex == 1 && ProcessorsList.SelectedIndex > -1)
                Config.Instance.Processors.Remove((CallProcessor)ProcessorsList.SelectedItem);
        }
        private void ConfigSaveButton_Click(object sender, RoutedEventArgs e)
        {
            if (Config.Save(this))
                TimeWindowShow.ShowTimeDialog(this);
        }
        private void CloseButton_Click(object sender, RoutedEventArgs e)=>this.Close();
        


        private void UserTextEditor_Loaded(object sender, RoutedEventArgs e)
        {
            UserTextEditor_DataContextChanged(sender, new());
        }
        private void UserTextEditor_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            UserTextEditor te = ((UserTextEditor)sender);

            if (te.DataContext is CallProcessor cp)
            {
                te.DependencyText = te.Tag switch
                {
                    "1" => cp.SuccessValidatedExpression,
                    "2" => cp.ProgressScript,
                    "3" => cp.GetProgressValueExpression,
                    _ => throw new NotImplementedException()
                };
            }
            if (te.DataContext is AdvancedParametersSchemeModule module)
                te.DependencyText = module.Command;
        }
        private void UserTextEditor_OnEditorStateChange(object sender, RoutedEventArgs e)
        {
            UserTextEditor te = ((UserTextEditor)sender);

            if (!te.IsReadOnly)
                return;

            if (te.DataContext is CallProcessor cp)
            {
                switch (te.Tag)
                {
                    case "1":
                        cp.SuccessValidatedExpression = te.Text;
                        return;
                    case "2":
                        cp.ProgressScript = te.Text;
                        return;
                    case "3":
                        cp.GetProgressValueExpression = te.Text;
                        return;
                    default:
                        throw new NotImplementedException();
                }
            }
            if (te.DataContext is AdvancedParametersSchemeModule module)
                module.Command = te.Text;
        }

        //private void SchemeList_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        //{
        //    if(!e.Handled)
        //    {
        //        e.Handled = true;
        //        if (((Control)sender).Parent is UIElement parent)
        //            parent.RaiseEvent(new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta) { RoutedEvent = MouseWheelEvent, Source = sender });
        //    }
        //}

        private void InsertText_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            //ContextMenuService.GetPlacementTarget(LogicalTreeHelper.GetParent(sender as MenuItem))

            if (sender is not MenuItem menuItem)
                return;
            if (menuItem.Parent is not ContextMenu cm)
                return;
            if (ContextMenuService.GetPlacementTarget(cm) is not UserTextEditor te)
                return;

            switch (menuItem.Tag)
            {
                case "1":
                    te.Document.Insert(te.CaretOffset, $"\"{ParametersSign.InputSignName}\"");
                    break;
                case "FFmpegInputs":
                    te.Document.Insert(te.CaretOffset, $"{ParametersSign.InputSignNames_FFmpeg}");
                    break;
                case "InputSCount":
                    te.Document.Insert(te.CaretOffset, $"{ParametersSign.InputSCount}");
                    break;
                case "2":
                    te.Document.Insert(te.CaretOffset, $"\"{ParametersSign.OutputSignName}\"");
                    break;
                case "3":
                    te.Document.Insert(te.CaretOffset, ParametersSign.STime);
                    break;
                case "4":
                    te.Document.Insert(te.CaretOffset, ParametersSign.ETime);
                    break;
                default:
                    te.Document.Insert(te.CaretOffset, ParametersSign.Sign);
                    break;
            }

            te.EnableEdit();
            
        }

        private void HelpButton_Click(object sender, RoutedEventArgs e)
        {
            Helps.ShowHelp();
        }
        
        #region 方案拖动排序
        private void SchemeList_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            FrameworkElement? fe = sender as FrameworkElement;

            if (fe != null && e.LeftButton == MouseButtonState.Pressed)
            {
                fe = (FrameworkElement)e.OriginalSource;
                if (fe is null)
                    return;
                while (fe!.DataContext is not AdvancedParametersSchemeModule)
                {
                    fe = VisualTreeHelper.GetParent(fe) as FrameworkElement;
                    if (fe is null)
                        return;
                }
                DragDrop.DoDragDrop(fe, new DataObject(fe.DataContext), DragDropEffects.Copy);
            }
        }
        private void SchemeList_PreviewDragOver(object sender, DragEventArgs e)
        {
            DependencyObject DO = (DependencyObject)sender;
            while (DO is not ScrollViewer)
                DO = VisualTreeHelper.GetParent(DO);
            ScrollViewer SV = (ScrollViewer)DO;
            double y = e.GetPosition(SV).Y;
            if (y < 25)
            {
                SV.ScrollToVerticalOffset(SV.VerticalOffset - Config.Instance.SchemeSetListDragScrollSpeed);
            }
            else if (y > SV.ActualHeight - 25)
            {
                SV.ScrollToVerticalOffset(SV.VerticalOffset + Config.Instance.SchemeSetListDragScrollSpeed);
            }
            e.Handled = true;
        }
        private void SchemeList_PreviewDrop(object sender, DragEventArgs e)
        {
            e.Handled = true;
            AdvancedParametersSchemeModule? DragSource = e.Data.GetData(typeof(AdvancedParametersSchemeModule)) as AdvancedParametersSchemeModule;
            FrameworkElement? PickItem = e.OriginalSource as FrameworkElement;

            while (PickItem is not ListBoxItem && PickItem is not null)
                PickItem = (FrameworkElement)VisualTreeHelper.GetParent(PickItem);

            AdvancedParametersSchemeModule? PickSource = PickItem?.DataContext as AdvancedParametersSchemeModule;
            if (DragSource is null || PickItem is null || e.Effects != DragDropEffects.Copy)
                return;

            //拖拽到空白区，直接最后一个
            if (PickItem is null)
            {
                Config.Instance.SchemeModules.Move(Config.Instance.SchemeModules.IndexOf(DragSource), Config.Instance.SchemeModules.Count - 1);
                return;
            }

            double MouseY = e.GetPosition(PickItem).Y;
            double CenterY = PickItem.ActualHeight / 2;

            int PickIndex = Config.Instance.SchemeModules.IndexOf(PickSource!);

            if (MouseY > CenterY)
                ++PickIndex;
            if (PickIndex < 0)
                PickIndex = 0;
            if (PickIndex >= Config.Instance.SchemeModules.Count)
                PickIndex = Config.Instance.SchemeModules.Count - 1;
            Config.Instance.SchemeModules.Move(Config.Instance.SchemeModules.IndexOf(DragSource), PickIndex);

        }

        #endregion

        
    }
}
